<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片覆盖-图片懒加载</title>
</head>

<body>
    <style>
        .root img {
            max-width: 100%;
            max-height: auto;
        }
    </style>
    <div class="root">
        <img data-src="https://sofile.cn/wp-content/uploads/img_test/1.jpg"
            src="https://sofile.cn/wp-content/uploads/img_test/img.png">
        <img data-src="https://sofile.cn/wp-content/uploads/img_test/2.jpg"
            src="https://sofile.cn/wp-content/uploads/img_test/img.png">
        <img data-src="https://sofile.cn/wp-content/uploads/img_test/3.jpg"
            src="https://sofile.cn/wp-content/uploads/img_test/img.png">
        <img data-src="https://sofile.cn/wp-content/uploads/img_test/4.jpg"
            src="https://sofile.cn/wp-content/uploads/img_test/img.png">
        <img data-src="https://sofile.cn/wp-content/uploads/img_test/5.jpg"
            src="https://sofile.cn/wp-content/uploads/img_test/img.png">
    </div>
    <script>
        //回调函数
        const observer = new IntersectionObserver(entries => {
            for (const i of entries) {//遍历数组entries中的每一个值
                if (i.isIntersecting) { // 当目标元素出现在视图内
                    const img = i.target;//被观察目标的dom节点
                    const trueSrc = img.getAttribute("data-src");//拿到data-src中的值
                    setTimeout(() => {
                        img.setAttribute("src", trueSrc);//添加src属性，覆盖原有属性
                    }, 3000);// 方便展示懒加载效果
                    observer.unobserve(img); // 停止监听此元素
                }
            }
        });

        //监听所有图片
        const images = document.getElementsByTagName("img");
        for (const i of images) {
            observer.observe(i);//开始观察img元素
        }
    </script>

</body>

</html>